package cn.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class TrimFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		arg2.doFilter(new myReq(request), arg1);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

	class myReq extends HttpServletRequestWrapper {

		public myReq(HttpServletRequest request) {
			super(request);

		}

		@Override
		public String getParameter(String name) {
			// TODO Auto-generated method stub

			return super.getParameter(name).trim();

		}

		@Override
		public Map<String, String[]> getParameterMap() {

			return super.getParameterMap();
		}

		@Override
		public String[] getParameterValues(String name) {
			String r[] = super.getParameterValues(name);

			if (r == null) {
				return null;
			}
			for (int i = 0; i < r.length; i++) {

				r[i] = r[i].trim();

			}
			return r;
		}
	}
}
